﻿using System;
using System.Web;

namespace M.Web
{
	/// <summary>
	/// 用于WebForm开发的友情工具库
	/// </summary>
	public static class Util
	{
		/// <summary>
		/// 获得当前页面客户端的IP
		/// </summary>
		/// <returns>当前页面客户端的IP</returns>
		public static string GetIP()
		{
			string result = String.Empty;
			result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
			if (null == result || result == String.Empty)
			{
				result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
			}
			if (null == result || result == String.Empty)
			{
				result = HttpContext.Current.Request.UserHostAddress;
			}
			if (null == result || result == String.Empty)
			{
				return "0.0.0.0";
			}
			return result;
		}

		/// <summary>
		/// 判断当前请求是不是POST请求
		/// </summary>
		/// <returns>是否接收到了Post请求</returns>
		public static bool IsPost()
		{
			return HttpContext.Current.Request.HttpMethod.Equals("POST");
		}
		/// <summary>
		/// 判断当前请求是不是GET请求
		/// </summary>
		/// <returns>是否接收到了Get请求</returns>
		public static bool IsGet()
		{
			return HttpContext.Current.Request.HttpMethod.Equals("GET");
		}

		/// <summary>
		/// 返回指定的服务器变量信息
		/// </summary>
		/// <param name="strName">服务器变量名</param>
		/// <returns>服务器变量信息</returns>
		public static string GetServerString(string strName)
		{
			return (HttpContext.Current.Request.ServerVariables[strName] == null) ? "" : HttpContext.Current.Request.ServerVariables[strName].ToString();
		}

		/// <summary>
		/// 返回请求页面地址
		/// </summary>
		/// <returns>请求页面地址</returns>
		public static string GetUrlReferrer()
		{
			string requestUrl = null;
			try
			{
				requestUrl = HttpContext.Current.Request.UrlReferrer.ToString();
			}
			catch { }
			if (requestUrl == null)
				return "";
			return requestUrl;
		}

		/// <summary>
		/// 得到当前完整主机头
		/// </summary>
		/// <returns></returns>
		public static string GetCurrentFullHost()
		{
			HttpRequest request = System.Web.HttpContext.Current.Request;
			if (!request.Url.IsDefaultPort)
			{
				return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
			}
			return request.Url.Host;
		}

		/// <summary>
		/// 得到主机头
		/// </summary>
		/// <returns></returns>
		public static string GetHost()
		{
			return HttpContext.Current.Request.Url.Host;
		}


		/// <summary>
		/// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
		/// </summary>
		/// <returns>原始 URL</returns>
		public static string GetRawUrl()
		{
			return HttpContext.Current.Request.RawUrl;
		}

		/// <summary>
		/// 判断当前访问是否来自浏览器软件
		/// </summary>
		/// <returns>当前访问是否来自浏览器软件</returns>
		public static bool IsBrowserGet()
		{
			string[] browserNames = { "ie", "opera", "netscape", "mozilla", "webkit" };
			string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
			for (int i = 0; i < browserNames.Length; i++)
			{
				if (curBrowser.IndexOf(browserNames[i]) >= 0)
					return true;
			}
			return false;
		}

		/// <summary>
		/// 判断是否来自搜索引擎链接
		/// </summary>
		/// <returns>是否来自搜索引擎链接</returns>
		public static bool IsSearchEnginesGet()
		{
			string[] searchEngines = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "bing" };
			string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
			for (int i = 0; i < searchEngines.Length; i++)
			{
				if (tmpReferrer.IndexOf(searchEngines[i]) >= 0)
					return true;
			}
			return false;
		}

		/// <summary>
		/// 获得当前完整Url地址
		/// </summary>
		/// <returns>当前完整Url地址</returns>
		public static string GetUrl()
		{
			return HttpContext.Current.Request.Url.ToString();
		}

		/// <summary>
		/// 获得当前页面的名称
		/// </summary>
		/// <returns>当前页面的名称</returns>
		public static string GetPageName()
		{
			string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
			return urlArr[urlArr.Length - 1].ToLower();
		}

		/// <summary>
		/// 返回表单或Url参数的总个数
		/// </summary>
		/// <returns></returns>
		public static int GetParamCount()
		{
			return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
		}

		/// <summary>
		/// 检查请求是否来自本地
		/// </summary>
		/// <returns></returns>
		public static bool IsLocalPost()
		{
			string queryUrl = GetServerString("HTTP_REFERER");
			string hostName = GetServerString("SERVER_NAME");
			if (queryUrl.Length == 0)
				return false;
			if (queryUrl.Length - 7 < hostName.Length)
				return false;
			return (queryUrl.Substring(7, hostName.Length) == hostName);
		}
		/// <summary>
		/// 获取WebConfig中的AppSettings
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string GetAppConfig(string key)
		{
			return System.Web.Configuration.WebConfigurationManager.AppSettings[key];
		}

		/// <summary>
		/// Url编码 QueryString
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static string SetQueryString(string value)
		{
			return (value == null) ? "" : UrlEncode(value);
		}

		/// <summary>
		/// 获得指定Url参数的值
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public static string GetQueryString(string name)
		{
			return (HttpContext.Current.Request.QueryString[name] == null) ? "" : UrlDecode(HttpContext.Current.Request.QueryString[name]);
		}

		/// <summary>
		/// 获得指定表单参数的值
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public static string GetFormString(string name)
		{
			return (HttpContext.Current.Request.Form[name] == null) ? "" : HttpContext.Current.Request.Form[name];
		}

		/// <summary>
		/// 获得指定请求参数的值
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public static string GetString(string name)
		{
			return (HttpContext.Current.Request[name] == null) ? "" : HttpContext.Current.Request[name];
		}

		/// <summary>
		/// 获取指定Url参数的int类型值
		/// </summary>
		/// <param name="name"></param>
		/// <param name="defaultValue"></param>
		/// <returns></returns>
		public static int GetQueryInt(string name, int defaultValue)
		{
			return M.Util.ObjectToInt(GetQueryString(name), defaultValue);
		}

		/// <summary>
		/// 获取指定表单参数的int类型值
		/// </summary>
		/// <param name="name"></param>
		/// <param name="defaultValue"></param>
		/// <returns></returns>
		public static int GetFormInt(string name, int defaultValue)
		{
			return M.Util.ObjectToInt(GetFormString(name), defaultValue);
		}

		/// <summary>
		/// 获取指定请求参数的int类型值
		/// </summary>
		/// <param name="name"></param>
		/// <param name="defaultValue"></param>
		/// <returns></returns>
		public static int GetInt(string name, int defaultValue)
		{
			return M.Util.ObjectToInt(GetString(name), defaultValue);
		}

		/// <summary>
		/// 获取指定Url参数的float类型值
		/// </summary>
		/// <param name="name"></param>
		/// <param name="defaultValue"></param>
		/// <returns></returns>
		public static float GetQueryFloat(string name, float defaultValue)
		{
			return M.Util.ObjectToFloat(GetQueryString(name), defaultValue);
		}

		/// <summary>
		/// 获取指定表单参数的float类型值
		/// </summary>
		/// <param name="name"></param>
		/// <param name="defaultValue"></param>
		/// <returns></returns>
		public static float GetFormFloat(string name, float defaultValue)
		{
			return M.Util.ObjectToFloat(GetFormString(name), defaultValue);
		}

		/// <summary>
		/// 获取指定请求参数的float类型值
		/// </summary>
		/// <param name="name"></param>
		/// <param name="defaultValue"></param>
		/// <returns></returns>
		public static float GetFloat(string name, float defaultValue)
		{
			return M.Util.ObjectToFloat(GetString(name), defaultValue);
		}

		/// <summary>
		/// 获取绝对路径
		/// </summary>
		/// <param name="path">相对路径</param>
		/// <returns></returns>
		public static string GetPhysicsPath(string path)
		{
			return HttpContext.Current.Server.MapPath(path);
		}

		/// <summary>
		/// 返回 HTML 字符串的编码结果
		/// </summary>
		/// <param name="str">字符串</param>
		/// <returns>编码结果</returns>
		public static string HtmlEncode(string str)
		{
			return HttpUtility.HtmlEncode(str);
		}

		/// <summary>
		/// 返回 HTML 字符串的解码结果
		/// </summary>
		/// <param name="str">字符串</param>
		/// <returns>解码结果</returns>
		public static string HtmlDecode(string str)
		{
			return HttpUtility.HtmlDecode(str);
		}

		/// <summary>
		/// 返回 URL 字符串的编码结果
		/// </summary>
		/// <param name="str">字符串</param>
		/// <returns>编码结果</returns>
		public static string UrlEncode(string str)
		{
			return HttpUtility.UrlEncode(str);
		}

		/// <summary>
		/// 返回 URL 字符串的编码结果
		/// </summary>
		/// <param name="str">字符串</param>
		/// <returns>解码结果</returns>
		public static string UrlDecode(string str)
		{
			return HttpUtility.UrlDecode(str);
		}

		/// <summary>
		/// 写入Cookie 页面级过期
		/// </summary>
		/// <param name="cookieName"></param>
		/// <param name="name"></param>
		/// <param name="value"></param>
		public static void WriteCookies(string cookieName, string name, string value)
		{
			WriteCookies(-1, cookieName, name, value);
		}

		/// <summary>
		/// 写入Cookie 页面级过期
		/// </summary>
		/// <param name="cookieName"></param>
		/// <param name="values"></param>
		public static void WriteCookies(string cookieName, System.Collections.Specialized.NameValueCollection values)
		{
			WriteCookies(-1, cookieName, values);
		}

		/// <summary>
		/// 写入Cookie 指定过期时间 以日为单位
		/// </summary>
		/// <param name="expires"></param>
		/// <param name="cookieName"></param>
		/// <param name="name"></param>
		/// <param name="value"></param>
		public static void WriteCookies(int expires, string cookieName, string name, string value)
		{
			System.Collections.Specialized.NameValueCollection values = new System.Collections.Specialized.NameValueCollection();
			values.Add(name, value);
			WriteCookies(expires, cookieName, values);
		}

		/// <summary>
		/// 写入Cookie 指定过期时间 以日为单位
		/// </summary>
		/// <param name="expires"></param>
		/// <param name="cookieName"></param>
		/// <param name="values"></param>
		public static void WriteCookies(int expires, string cookieName, System.Collections.Specialized.NameValueCollection values)
		{
			HttpCookie cookie = new HttpCookie(string.Format("{0}_{1}", Util.GetProcessName(), cookieName));
			foreach (string key in values.Keys)
				cookie.Values.Add(key, values[key]);
			if (expires > 0)
				cookie.Expires = DateTime.Now.AddDays(expires);
			HttpContext.Current.Response.Cookies.Add(cookie);
		}

		/// <summary>
		/// 获取Cookies
		/// </summary>
		/// <param name="cookieName"></param>
		/// <param name="keyName"></param>
		/// <returns></returns>
		public static string GetCookies(string cookieName, string keyName)
		{
			if (HttpContext.Current.Request.Cookies[string.Format("{0}_{1}", Util.GetProcessName(), cookieName)] == null)
				return "";
			else
				return (HttpContext.Current.Request.Cookies[string.Format("{0}_{1}", Util.GetProcessName(), cookieName)][keyName] == null) ? "" : UrlDecode(HttpContext.Current.Request.Cookies[string.Format("{0}_{1}", Util.GetProcessName(), cookieName)][keyName]);
		}

		/// <summary>
		/// 清理Cookies
		/// </summary>
		/// <param name="cookieName"></param>
		public static void RemoveCookies(string cookieName)
		{
			HttpContext.Current.Response.Cookies[string.Format("{0}_{1}", Util.GetProcessName(), cookieName)].Values.Clear();
		}
		/// <summary>
		/// 设置Session超时时间
		/// </summary>
		/// <param name="mins"></param>
		public static void SetSessionTimedout(int mins)
		{
			HttpContext.Current.Session.Timeout = mins;
		}
		/// <summary>
		/// 写Session
		/// </summary>
		/// <param name="sessionName">Session名称</param>
		/// <param name="value">值</param>
		public static void WriteSession(string sessionName, object value)
		{
			HttpContext.Current.Session[string.Format("{0}_{1}", Util.GetProcessName(), sessionName)] = value;
		}

		/// <summary>
		/// 获取Session
		/// </summary>
		/// <param name="sessionName">Session名称</param>
		/// <returns>值</returns>
		public static object GetSession(string sessionName)
		{
			return HttpContext.Current.Session[string.Format("{0}_{1}", Util.GetProcessName(), sessionName)];
		}

		/// <summary>
		/// 清理Session
		/// </summary>
		/// <param name="sessionName"></param>
		public static void RemoveSession(string sessionName)
		{
			HttpContext.Current.Session.Remove(string.Format("{0}_{1}", Util.GetProcessName(), sessionName));
		}

		/// <summary>
		/// 写缓存
		/// </summary>
		/// <param name="cacheName"></param>
		/// <param name="value"></param>
		public static void WriteApplicationCache(string cacheName, object value)
		{
			HttpContext.Current.Application.Lock();
			HttpContext.Current.Application[string.Format("{0}_{1}", Util.GetProcessName(), cacheName)] = value;
			HttpContext.Current.Application.UnLock();
		}

		/// <summary>
		/// 获取缓存
		/// </summary>
		/// <param name="cacheName"></param>
		/// <returns></returns>
		public static object GetApplicationCache(string cacheName)
		{
			return HttpContext.Current.Application[string.Format("{0}_{1}", Util.GetProcessName(), cacheName)];
		}

		/// <summary>
		/// 清理缓存
		/// </summary>
		/// <param name="cacheName"></param>
		public static void RemoveApplicationCache(string cacheName)
		{
			HttpContext.Current.Application.Remove(string.Format("{0}_{1}", Util.GetProcessName(), cacheName));
		}

		/// <summary>
		/// 根据主机相关信息获取一个过程名 用于Cookies Session Application 的名称
		/// </summary>
		/// <returns></returns>
		public static string GetProcessName()
		{
			string result = GetServerString("SERVER_NAME") + GetServerString("URL");
			string oldValue = GetServerString("SCRIPT_NAME").Split('/')[GetServerString("SCRIPT_NAME").Split('/').Length - 1];
			if (oldValue.Length > 0) result = result.Replace(oldValue, "");
			result = result.Substring(0, result.IndexOf('/'));
			return result;
		}
		/// <summary>
		/// 获取拼接网址
		/// </summary>
		/// <param name="url"></param>
		/// <returns></returns>
		public static string GetRequestUrl(params string[] url)
		{
			if (url == null || url.Length == 0) return string.Empty;
			return string.Join("/", url);
		}
	}
}
